package com.ljc;

import com.ljc.dto.ListNode;

/**
 * @author ljchen on 2022/1/21
 *
 * You are given two non-empty linked lists representing two non-negative integers.
 * The digits are stored in reverse order, and each of their nodes contains a single digit.
 * Add the two numbers and return the sum as a linked list.
 * You may assume the two numbers do not contain any leading zero, except the number 0 itself.
 *
 * Input: l1 = [2,4,3], l2 = [5,6,4]
 * Output: [7,0,8]
 * Explanation: 342 + 465 = 807.
 * Example 2:
 *
 * Input: l1 = [0], l2 = [0]
 * Output: [0]
 * Example 3:
 *
 * Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
 * Output: [8,9,9,9,0,0,0,1]
 *
 */
public class M2AddTwoNumbers {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        ListNode l2 = new ListNode(4);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(5);
        ListNode l5 = new ListNode(6);
        ListNode l6 = new ListNode(4);

        l1.next = l2;
        l2.next = l3;

        l4.next = l5;
        l5.next = l6;

        ListNode result = addTwoNumbers(l1, l4);
        System.out.println(result.val);
        System.out.println(result.next.val);
        System.out.println(result.next.next.val);

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;
        int carry = 0;
        int i =1;
        while (l1 != null || l2 != null) {
            int n1 = l1 != null ? l1.val : 0;
            System.out.println("第" + i + "次迭代 n1: " + n1);
            int n2 = l2 != null ? l2.val : 0;
            System.out.println("第" + i + "次迭代 n2: " + n2);
            int sum = n1 + n2 + carry;
            System.out.println("sum: " + sum);
            if (head == null) {
                head = tail = new ListNode(sum % 10);
                System.out.println("第" + i + "次迭代 head: " + head.val);
            } else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
                System.out.println("第" + i + "次迭代 tail: " + tail.val);
            }
            carry = sum / 10;
            System.out.println("第" + i + "次迭代 carry/10: " + carry);
            if (l1 != null) {
                l1 = l1.next;
                System.out.println("第" + i + "次迭代 l1.next: " + l1);
            }
            if (l2 != null) {
                l2 = l2.next;
                System.out.println("第" + i + "次迭代 l2.next: " + l2);
            }
            i++;
        }
        if (carry > 0) {
            tail.next = new ListNode(carry);
            System.out.println("第" + i + "次迭代 tail.next: " + tail.next);
        }
        return head;
    }

}
